import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, ProgressBar, SegmentedButtons, Chip, TextInput } from 'react-native-paper';
import Slider from '@react-native-community/slider';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export default function PreferencesScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [preferredGender, setPreferredGender] = useState(userInfo?.matchPreferences?.preferredGender || '');
  const [minAge, setMinAge] = useState(userInfo?.matchPreferences?.minAge?.toString() || '18');
  const [maxAge, setMaxAge] = useState(userInfo?.matchPreferences?.maxAge?.toString() || '50');
  const [minHeight, setMinHeight] = useState(userInfo?.matchPreferences?.minHeight?.toString() || '150');
  const [maxHeight, setMaxHeight] = useState(userInfo?.matchPreferences?.maxHeight?.toString() || '190');
  const [preferredEducation, setPreferredEducation] = useState<string[]>(userInfo?.matchPreferences?.preferredEducation || []);
  const [preferredOccupation, setPreferredOccupation] = useState('');
  const [preferredOccupations, setPreferredOccupations] = useState<string[]>(userInfo?.matchPreferences?.preferredOccupations || []);
  const [preferredDistance, setPreferredDistance] = useState(userInfo?.matchPreferences?.preferredDistance?.toString() || '50');
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 添加职业偏好
  const addOccupation = () => {
    if (preferredOccupation.trim() && !preferredOccupations.includes(preferredOccupation.trim())) {
      setPreferredOccupations([...preferredOccupations, preferredOccupation.trim()]);
      setPreferredOccupation('');
    }
  };

  // 移除职业偏好
  const removeOccupation = (occupation: string) => {
    setPreferredOccupations(preferredOccupations.filter(o => o !== occupation));
  };

  // 切换教育程度偏好
  const toggleEducation = (education: string) => {
    if (preferredEducation.includes(education)) {
      setPreferredEducation(preferredEducation.filter(e => e !== education));
    } else {
      setPreferredEducation([...preferredEducation, education]);
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    if (!preferredGender) {
      Alert.alert('提示', '请选择您偏好的性别');
      return;
    }

    setIsLoading(true);
    try {
      // 更新用户匹配偏好
      const matchPreferences = {
        preferredGender,
        minAge: parseInt(minAge, 10),
        maxAge: parseInt(maxAge, 10),
        minHeight: parseInt(minHeight, 10),
        maxHeight: parseInt(maxHeight, 10),
        preferredEducation,
        preferredOccupations,
        preferredDistance: parseInt(preferredDistance, 10)
      };
      
      const success = await updateProfile({ matchPreferences });

      if (success) {
        // 完成设置
        router.push('/profile-setup/complete');
      } else {
        Alert.alert('错误', '更新匹配偏好失败，请重试');
      }
    } catch (error) {
      console.error('Update preferences error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>匹配偏好</ThemedText>
            <ThemedText style={styles.subtitle}>
              设置您的匹配偏好，帮助我们为您筛选最合适的人
            </ThemedText>
          </View>

          <ProgressBar 
            progress={6/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>偏好性别</ThemedText>
              <SegmentedButtons
                value={preferredGender}
                onValueChange={setPreferredGender}
                buttons={[
                  { value: 'male', label: '男' },
                  { value: 'female', label: '女' },
                  { value: 'both', label: '不限' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>年龄范围: {minAge} - {maxAge}岁</ThemedText>
              <View style={styles.rangeContainer}>
                <View style={styles.sliderContainer}>
                  <Slider
                    value={parseInt(minAge, 10)}
                    onValueChange={(value: number) => {
                      const newValue = Math.min(value, parseInt(maxAge, 10) - 1);
                      setMinAge(newValue.toString());
                    }}
                    minimumValue={18}
                    maximumValue={80}
                    step={1}
                    minimumTrackTintColor="#ccc"
                    maximumTrackTintColor={tintColor}
                    thumbTintColor={tintColor}
                    style={styles.slider}
                  />
                  <View style={styles.sliderLabels}>
                    <ThemedText>18岁</ThemedText>
                    <ThemedText>最小年龄: {minAge}岁</ThemedText>
                  </View>
                </View>

                <View style={styles.sliderContainer}>
                  <Slider
                    value={parseInt(maxAge, 10)}
                    onValueChange={(value: number) => {
                      const newValue = Math.max(value, parseInt(minAge, 10) + 1);
                      setMaxAge(newValue.toString());
                    }}
                    minimumValue={18}
                    maximumValue={80}
                    step={1}
                    minimumTrackTintColor={tintColor}
                    maximumTrackTintColor="#ccc"
                    thumbTintColor={tintColor}
                    style={styles.slider}
                  />
                  <View style={styles.sliderLabels}>
                    <ThemedText>最大年龄: {maxAge}岁</ThemedText>
                    <ThemedText>80岁</ThemedText>
                  </View>
                </View>
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>身高范围: {minHeight} - {maxHeight}cm</ThemedText>
              <View style={styles.rangeContainer}>
                <View style={styles.sliderContainer}>
                  <Slider
                    value={parseInt(minHeight, 10)}
                    onValueChange={(value: number) => {
                      const newValue = Math.min(value, parseInt(maxHeight, 10) - 5);
                      setMinHeight(newValue.toString());
                    }}
                    minimumValue={140}
                    maximumValue={220}
                    step={1}
                    minimumTrackTintColor="#ccc"
                    maximumTrackTintColor={tintColor}
                    thumbTintColor={tintColor}
                    style={styles.slider}
                  />
                  <View style={styles.sliderLabels}>
                    <ThemedText>140cm</ThemedText>
                    <ThemedText>最小身高: {minHeight}cm</ThemedText>
                  </View>
                </View>

                <View style={styles.sliderContainer}>
                  <Slider
                    value={parseInt(maxHeight, 10)}
                    onValueChange={(value: number) => {
                      const newValue = Math.max(value, parseInt(minHeight, 10) + 5);
                      setMaxHeight(newValue.toString());
                    }}
                    minimumValue={140}
                    maximumValue={220}
                    step={1}
                    minimumTrackTintColor={tintColor}
                    maximumTrackTintColor="#ccc"
                    thumbTintColor={tintColor}
                    style={styles.slider}
                  />
                  <View style={styles.sliderLabels}>
                    <ThemedText>最大身高: {maxHeight}cm</ThemedText>
                    <ThemedText>220cm</ThemedText>
                  </View>
                </View>
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>教育程度偏好</ThemedText>
              <ThemedText style={styles.subLabel}>选择您接受的教育程度（可多选）</ThemedText>
              
              <View style={styles.chipContainer}>
                {['high_school', 'college', 'bachelor', 'master', 'phd'].map((education, index) => {
                  const labels: Record<string, string> = {
                    'high_school': '高中',
                    'college': '大专',
                    'bachelor': '本科',
                    'master': '硕士',
                    'phd': '博士'
                  };
                  
                  return (
                    <Chip
                      key={index}
                      selected={preferredEducation.includes(education)}
                      onPress={() => toggleEducation(education)}
                      style={[
                        styles.chip,
                        preferredEducation.includes(education) && { backgroundColor: tintColor + '20' }
                      ]}
                      textStyle={[
                        styles.chipText,
                        preferredEducation.includes(education) && { color: tintColor }
                      ]}
                    >
                      {labels[education]}
                    </Chip>
                  );
                })}
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>职业偏好</ThemedText>
              <ThemedText style={styles.subLabel}>添加您偏好的职业（可选）</ThemedText>
              
              <View style={styles.inputWithButton}>
                <TextInput
                  value={preferredOccupation}
                  onChangeText={setPreferredOccupation}
                  mode="outlined"
                  placeholder="例如：医生、教师、工程师"
                  style={styles.customInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  onSubmitEditing={addOccupation}
                />
                <Button
                  mode="contained"
                  onPress={addOccupation}
                  style={styles.addButton}
                  theme={{ roundness: 10 }}
                >
                  添加
                </Button>
              </View>

              <View style={styles.chipContainer}>
                {preferredOccupations.map((occupation, index) => (
                  <Chip
                    key={index}
                    onClose={() => removeOccupation(occupation)}
                    style={styles.chip}
                    textStyle={styles.chipText}
                  >
                    {occupation}
                  </Chip>
                ))}
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>最大距离: {preferredDistance}公里</ThemedText>
              <View style={styles.sliderContainer}>
                <Slider
                  value={parseInt(preferredDistance, 10)}
                  onValueChange={(value: number) => setPreferredDistance(value.toString())}
                  minimumValue={1}
                  maximumValue={500}
                  step={1}
                  minimumTrackTintColor={tintColor}
                  maximumTrackTintColor="#ccc"
                  thumbTintColor={tintColor}
                  style={styles.slider}
                />
                <View style={styles.sliderLabels}>
                  <ThemedText>1公里</ThemedText>
                  <ThemedText>{preferredDistance}公里</ThemedText>
                  <ThemedText>500公里</ThemedText>
                </View>
              </View>
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
            >
              完成设置
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.back()}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginTop: 40,
    marginBottom: 30,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    marginBottom: 10,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    marginBottom: 30,
  },
  formContainer: {
    marginBottom: 30,
  },
  formGroup: {
    marginBottom: 25,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  subLabel: {
    fontSize: 14,
    marginBottom: 12,
    opacity: 0.7,
  },
  segmentedButtons: {
    marginBottom: 10,
  },
  rangeContainer: {
    marginBottom: 15,
  },
  sliderContainer: {
    marginBottom: 15,
  },
  slider: {
    height: 40,
  },
  sliderLabels: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 15,
  },
  chip: {
    margin: 4,
  },
  chipText: {
    fontSize: 14,
  },
  inputWithButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  customInput: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  addButton: {
    marginLeft: 10,
  },
  buttonContainer: {
    marginTop: 'auto',
    marginBottom: 20,
  },
  button: {
    marginBottom: 15,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  backButton: {
    borderColor: '#ccc',
  },
  backButtonText: {
    fontSize: 16,
  },
});
